//
//$Id: adjacent.cpp 679 2011-03-12 16:50:06Z andrew.tsyganov $
#include "stdafx.h"
#include "include/adjacent.h"

u_t Adjacent::insert(u_t const sym_id, u_t const dst_id) 
{ 
	Adjacent::iterator it = find(sym_id);

	if (it != (*this).end())
	{
		u_t old_size = it->second.size();
		it->second.insert(dst_id);
		u_t new_size = it->second.size();
		return new_size - old_size;
	}
	else
	{
		(*this)[sym_id].insert(dst_id); 
		return 1;
	}
}

u_t Adjacent::insert(u_t const sym_id, Subset const& s)
{
	Adjacent::iterator it = find(sym_id);

	if (it != (*this).end())
	{
		u_t old_size = it->second.size();
		it->second |= s;
		u_t new_size = it->second.size();
		return new_size - old_size;
	}
	else
	{
		(*this)[sym_id] = s; 
		return s.size();
	}
}

u_t Adjacent::remove(u_t const sym_id, u_t const dst_id)
{
	Adjacent::iterator it = find(sym_id);

	if (it != (*this).end())
	{
		u_t old_size = it->second.size();
		it->second.remove(dst_id);
		u_t new_size = it->second.size();
		
		if (it->second.empty())
		{
			erase(it);
		}

		return old_size - new_size;
	}
	else
	{
		return 0;
	}
}

u_t Adjacent::remove()
{
	u_t n = 0;
	for (Adjacent::iterator it = (*this).begin(); it != (*this).end(); ++it)
	{
		n += it->second.size();
	}
	clear();
	return n;
}

bool Adjacent::contains(u_t const sym_id, u_t const dst_id) const
{
	Adjacent::const_iterator it = find(sym_id);

	if (it != (*this).end())
	{
		return it->second.contains(dst_id);
	}
	else
	{
		return false;
	}
}

u_t Adjacent::calc_Out_Transitions_Num() const
{
	u_t n = 0;
	for (Adjacent::const_iterator it = begin(); it != end(); ++it)
	{
		n += it->second.size();
	}
	return n;
}

u_t Adjacent::calc_Out_Transitions_Num(u_t const sym_id) const
{
	Adjacent::const_iterator it = find(sym_id);

	if (it != (*this).end())
	{
		return it->second.size();
	}
	else
	{
		return 0;
	}
}

u_t Adjacent::calc_In_Transitions_Num(u_t const dst_id) const
{
	u_t n = 0;
	for (Adjacent::const_iterator it = begin(); it != end(); ++it)
	{
		if (it->second.contains(dst_id))
		{
			++n;
		}
	}
	return n;
}

u_t Adjacent::calc_In_Transitions_Num(u_t const dst_id, u_t const sym_id) const
{
	return contains(sym_id, dst_id) ? 1 : 0; 
}

Subset const& Adjacent::get_Dst(u_t const sym_id) const 
{ 
	Adjacent::const_iterator it = find(sym_id);

	if (it != (*this).end())
	{
		return it->second; 
	}
	else
	{
		return kEmptyDst;
	}
}


//EOF!
